<?php
/**
 * Created by PhpStorm.
 * User: 96151
 * Date: 2019/1/4
 * Time: 11:10
 */
namespace app\common\service\swoole;
use app\common\library\CommonFun;
use app\common\service\ElkLog;
use Swoole\Http\Server;
use swoole_http_request;
use swoole_http_response;

class SwooleHttpServer
{
    CONST HOST = "0.0.0.0";
    CONST PORT = 9501;

    public $http = null;
    public function __construct( )
    {
        $this->http = new Server( self::HOST, self::PORT );
    }

    /**
     * 启动程序
     */
    public function start()
    {
        $this->http->set(
            [
                'worker_num' => 4,
                'max_request' => 1000,
                "daemonize"   => 1,
                "open_tcp_keepalive"  => 1,
                'http_parse_post' => true,
            ]
        );
//        $this->http->on('connect', [$this, 'onConnect']);
        $this->http->on('request', [$this, 'onRequest']);
        $this->http->on('close', [$this, 'onClose']);
        swoole_set_process_name("php_asynchronous_call_back");
        $this->http->start();
    }

    /**
     * 获取请求
     */
    public function onRequest( swoole_http_request $request, swoole_http_response $response )
    {
        ElkLog::write( array( "message"=> "Request", "data"=> $request, "response"=>$response ) );
        $request_uri = trim( $request->server['request_uri'], "/");
        $request_uri = explode( "/", $request_uri );

        $module = $request_uri[0];
        $method = $request_uri[1];
        if ( $request->server['request_method'] == 'GET' ){
            $data = $request->get;
        } else {
            $data = $request->post;
        }

        $data = $data ?: array();
        ksort( $data );
        $data = array_values( $data );
        $res = $this->call_back( $module, $method, $data );
        if ( is_array( $res ) ){
            CommonFun::json_encode2( $res );
        }

        $response->end( $res );
    }

    /**
     * 分发任务
     * @param $module
     * @param $method
     * @param array $data
     * @return bool|mixed
     */
    public function call_back( $module, $method, array $data )
    {
        // 检测类和方法是否存在
        if ( class_exists( $module ) && method_exists( $module, $method ) ){
            $res = call_user_func_array( array( $module, $method ), $data );
            return $res;
        } else {
            ElkLog::write( array( "message"=> "onReceiveError", "data"=> $data ) );
            return false;
        }
    }

    /**
     * 重启进程
     */
    public function reload()
    {
        $this->http->reload();
    }


    /**
     * 监听连接事件
     * @param $tcp
     * @param $fd
     * @param $reactor_id
     */
    public function onConnect($tcp, $fd, $reactorId)
    {
        echo "客户端id:{$fd}连接成功,来自于线程{$reactorId}\n";
    }


    /**
     * 监听关闭事件
     * @param $tcp
     * @param $fd
     */
    public function onClose($http, $fd)
    {
        echo "客户端id: {$fd} 关闭了连接\n";
    }






}